# -*- coding: utf-8 -*-
'''
Created on 2013-4-27

@author: dyq
'''
from Common.htmlHlep import Find
from Common.tool import tool
from Cms import config
from Cms.plus import  page,user
from Models import  models
import  hashlib,datetime,random
from django.db import transaction


@page.page_render(user.Admin())
def Index(request):
        '''
                            列表页
        '''
        list= models.Sys_Team.objects.all()
    
        return Find.View(request,list)
    
    
@page.page_render(user.Admin())
def List(request):
        '''
                            列表页
        '''
        purviewid=int(request.POST.get("PurviewTeamID",-1))
        state=int(request.POST.get("State",-1))
        nickName=request.POST.get("NickName",None)
        LoginAccount=request.POST.get("LoginAccount","")
        
        list=models.User_Account.objects.all()
        
        if LoginAccount!="":
            userinfoList=models.User_Login.objects.filter(Account=LoginAccount)
            if len(userinfoList)!=0:
                list= list.filter(UserId=userinfoList[0].UserId.UserId)
            else:
                list= list.filter(UserId="_")
        
        if purviewid!=-1:
            list= list.filter(PurviewTeamID=models.Sys_Team.objects.get(id=purviewid))
            
        if state!=-1:
            list= list.filter(State=state)
            
        if nickName!=None:
            list= list.filter(NickName__contains=nickName)       

        list=list.order_by("-CreateTtime") #倒序加上-号
        
        return Find.View(request,Find.paginator(request,list))

@page.page_render(user.Admin())
def View(request):
        '''
                            查看
        '''
        info =models.User_Account.objects.get(UserId=request.GET.get("UserId"))
        team= models.Sys_Team.objects.all()
        
        return Find.View(request,{"info":info,"Team":team})

@page.page_render(user.Admin())
def Edit(request):
        '''
                            编辑
        '''
        info =models.User_Account.objects.get(UserId=request.GET.get("UserId"))
       
        #验证权限
        ver=verify(request,info);
        if ver["error"]:
            return Find.JsonX(True, ver["txt"])
        
        team= models.Sys_Team.objects.all()
        
        return Find.View(request,{"info":info,"Team":team})
    
@page.page_render(user.Admin())
def DoEdit(request):
        '''
                            编辑
        '''
        info=models.User_Account.objects.get(UserId=request.POST.get("UserId"))
        
        #验证权限
        ver=verify(request,info);
        if ver["error"]:
            return Find.JsonX(True, ver["txt"])
        
        Find.UpdateModel(request,info)
        info.PurviewTeamID=models.Sys_Team.objects.get(id=request.POST.get("PurviewTeam"))
        
        print len(models.User_Account.objects.filter(NickName=info.NickName).exclude(UserId=info.UserId))
        
        if 0!=len(models.User_Account.objects.filter(NickName=info.NickName).exclude(UserId=info.UserId)):
            return Find.JsonX(True, "昵称已存在")
        
        info.save()
        
        user.user().Log(request,1, "编辑用户："+str(info.UserId))
        
        return Find.JsonX(False, "操作成功")
    
#事务处理
@page.page_render(user.Admin())
@transaction.commit_manually 
def DoBatch(request):
    try:
        dataOrderList=str(request.POST.get("AccountList")).split(',')
        stateBatch=int(request.POST.get("selectBatch",-1))
        for key in dataOrderList:
            info=models.User_Account.objects.get(UserId=key)
            
            #权限判断
            ver=verify(request,info);
            
            if stateBatch!=-1 and ver["error"]==False:
                info.State=stateBatch
            else:
                transaction.rollback()
                return Find.JsonX(True, ver["txt"])
            
            info.save()
        user.user().Log(request,1, "批量编辑用户  State："+str(stateBatch))
        transaction.commit()
    except Exception:
        transaction.rollback()
        
    return Find.JsonX(False, "操作成功")

#验证权限
def verify(request,userinfo):
      
        if userinfo.UserId==config.Config().SysAdminId:
            return  {"error":True,"txt":"创始人账号不能在这里修改"}
        
        if userinfo.PurviewTeamID.id > user.user().GetUser(request).PurviewTeamID.id:
            return  {"error":True,"txt":"您的权限不不足无法操作账号:"+str(userinfo.NickName)+""}
        
        return {"error":False}
    
@page.page_render(user.Admin())
def Add(request):
        '''
                            添加
        '''
        list= models.Sys_Team.objects.all()
       
        return Find.View(request, list)
    
@page.page_render(user.Admin())
@transaction.commit_manually 
def DoAdd(request):
        try:
            
            #注册账号
            account = models.User_Account(State=1,TypeId=0,
                                   UserId=tool.guid(),
                                   CreateTtime=datetime.datetime.now(),
                                   PurviewTeamID=models.Sys_Team.objects.get(id=request.POST.get("PurviewTeam")))
            Find.UpdateModel(request,account)
            
            #注册登录账号
            login = models.User_Login(Rowid=tool.guid(),
                                      UserId=account,State=1,
                                      Types=0,
                                      CreateTtime=datetime.datetime.now())
            Find.UpdateModel(request,login)
            login.PassWord=tool.Md5(login.PassWord)
            
            #验证权限
            ver=verify(request,account);
            if ver["error"]:
                transaction.rollback()
                return Find.JsonX(True, "新建账号的权限不能大于您的权限")
        
            if 0!=len(models.User_Account.objects.filter(NickName=account.NickName)):
                transaction.rollback()
                return Find.JsonX(True, "昵称已存在")
            
            if 0!=len(models.User_Login.objects.filter(Account=login.Account)):
                transaction.rollback()
                return Find.JsonX(True, "账号已存在")
        
            account.save()
            login.save()
            transaction.commit()
            
            user.user().Log(request,2, "添加用户  UserId："+str(account.UserId))
        except:
            transaction.rollback()
            
       
        return Find.JsonX(False,"添加成功")
    
@page.page_render(user.Admin())
def LoginList(request):
        list =models.User_Login.objects.filter(UserId=request.GET.get("UserId"))
        
        #验证权限
        if len(list)!=0:
            ver=verify(request,list[0].UserId);
            if ver["error"]:
                return Find.JsonX(True, ver["txt"])
        
        return Find.View(request,list)
    
@page.page_render(user.Admin())
def DoChangePassword(request):
        '''
                             重置密码
        '''
        oldpwd=str(random.randint(10000, 99999))
        info= models.User_Login.objects.get(Rowid=request.GET.get("Rowid"))
        
        #验证权限
        ver=verify(request,info.UserId);
        if ver["error"]:
            return Find.JsonX(True, ver["txt"])
        
        info.PassWord=tool.Md5(oldpwd)
        info.save()
        user.user().Log(request,1, "重置密码  Userid："+str(info.UserId.UserId))
        
        return Find.JsonX(False,"密码已被修改为:"+oldpwd)


    
    
    
    